<template>
  <div class="common-activity" :style="{ backgroundColor: bgColor }">
    <van-pull-refresh
      v-model="isRefresh"
      :disabled="disabled"
      @refresh="onDownRefresh"
    >
      <div v-if="isShowHeader" id="header">
        <!-- banner -->
        <div v-if="bannerList.length > 0" class="banner-wrap">
          <banner-list :bannerList="bannerList" />
        </div>
        <!-- 金刚位 -->
        <diamond-list
          v-if="diamondList.length > 0"
          :diamond-list="diamondList"
        />
        <!-- 生活频道 -->
        <lifeChannel
          v-if="lifeTabList.length > 0"
          :lifeTabList="lifeTabList"
          :conferenceName="conferenceName"
          :conferenceId="conferenceId"
          @open="open"
          @close="close"
        />
      </div>
      <!-- 频道 -->
      <div v-if="channelList.length > 1" class="fixed-tab-nav">
        <div id="tab-nav-wrap" :class="tabFixed ? 'isFixed' : ''">
          <div class="channel-list" :class="{ w100: channelList.length <= 4 }">
            <van-tabs
              v-model="activeIndex"
              class="van-tabs_custom_activity"
              @click="handleTagClick"
            >
              <van-tab
                v-for="tab in channelList"
                :key="tab.id"
                :title="tab.name"
                class="van-tab_custom"
              >
              </van-tab>
            </van-tabs>
          </div>
          <!-- 下拉按钮 -->
          <div
            v-if="channelList.length > 4"
            class="drop-down"
            @click="toggleChannel"
          >
            <img
              src="../../assets/images/activity/icon-down-select.png"
              alt=""
            />
          </div>
        </div>
      </div>
      <!-- 主内容区域 -->
      <van-list
        v-model="isLoading"
        :finished="isFinished"
        :finished-text="tip"
        :immediate-check="false"
        :style="{ minHeight: '100vh' }"
        @load="onLoadMore"
      >
        <!-- 商品列表 -->
        <div
          class="productList-wrapper"
          :class="{
            between: colType === 2,
            'col-3': colType === 3,
            pt48: tabFixed
          }"
        >
          <div v-for="(v, index) in list" :key="index">
            <insertCard
              v-if="v.isInsertCard"
              :insertCardObj="v"
              :colType="colType"
            />
            <template v-else>
              <activity v-if="type === 1" :index="index" :activityObj="v" />
              <one-col-product
                v-else-if="colType === 1"
                :product="v"
                @shareProduct="shareProduct(v, index)"
              />
              <two-col-product
                v-else-if="colType === 2"
                :product="v"
                @shareProduct="shareProduct(v, index)"
              />
              <three-col-product
                v-else-if="colType === 3"
                :product="v"
                @shareProduct="shareProduct(v, index)"
              />
            </template>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
    <!-- channel下拉选择弹窗 -->
    <channel-popup
      ref="channelPopupRef"
      :channelList="channelList"
      :curTabIndex="curTabIndex"
      @selectTab="selectTab"
    />
    <!-- 分享按钮 -->
    <div class="share-activity-btn" @click="sharePoster">分享</div>
    <!-- 海报 -->
    <poster :visible.sync="isShowPoster" :shareObj="shopInfo" />
  </div>
</template>
<script>
import { getYMD } from '@/utils/util';
import diamondList from './components/diamondList.vue';
import bannerList from './components/bannerList.vue';
import oneColProduct from './components/oneColProduct.vue';
import twoColProduct from './components/twoColProduct.vue';
import threeColProduct from './components/threeColProduct.vue';
import insertCard from './components/insertCard.vue';
import activity from './components/activity.vue';
import channelPopup from './components/channelPopup.vue';
import lifeChannel from './components/lifeChannel2.vue';
import poster from '@/components/poster/posterV2';
import { userInfo, shareInfo, dataInfo } from './json/commonActivity-1433';

export default {
  name: 'meetingPlace',
  components: {
    bannerList,
    diamondList,
    channelPopup,
    oneColProduct,
    twoColProduct,
    threeColProduct,
    insertCard,
    activity,
    lifeChannel,
    poster
  },
  data() {
    return {
      shareObj: {},
      notData: false,
      docHeight: document.documentElement.clientHeight,
      bgColor: '',
      conferenceId: '',
      conferenceName: '',
      bannerList: [],
      diamondList: [],
      channelList: [],
      tabFixed: false, // 是否固定channel区域
      channelId: null, // 选中的channelId
      curTabIndex: 0, // 当前选中的channel下标
      activeIndex: 0, // 跟频道popup联动的

      lifeTabList: [],

      type: 1, // 1:活动, 2:商品
      list: [],

      isRefresh: false, // 下拉刷新
      isLoading: false, // 上拉加载
      isFinished: false, // 上拉加载完毕
      offset: 10, // 滚动条与底部距离小于 offset 时触发load事件
      tip: '没有更多了',
      pageNum: 1, // 页码
      pageSize: 12, // 一页加载多少条
      isFirstLoading: true,

      // 分享海报信息
      shopInfo: {},
      isShowPoster: false, // 是否展示分享海报
      isAgent: false, // 是否是代理
      isScroll: false, // 是否滚动

      totalHeight: 0,
      throttleFn: null,
      conferenceSpVos: [],
      t1: 0,
      t2: 0,
      timer: null,
      disabled: false,
      domHeight: document.documentElement.clientHeight,
      showHeight: document.documentElement.clientHeight,
      heightChange: false
    };
  },
  computed: {
    isShowHeader() {
      return (
        this.bannerList.length > 0 ||
        this.diamondList.length > 0 ||
        this.lifeTabList.length > 0
      );
    },
    curTabName() {
      return this.channelList.length > 0
        ? this.channelList[this.curTabIndex].name
        : '';
    },
    // colType: 1: 列商品，2: 2列商品 3: 3列商品
    colType() {
      let colNum = 0;
      if (this.type === 2 && this.channelList.length > 0) {
        const { productShowStatus } = this.channelList[this.curTabIndex] || {};
        colNum = productShowStatus >= 0 ? productShowStatus : 1; // 兼容老数据
      }
      return colNum + 1;
    }
  },
  watch: {
    showHeight() {
      if (this.domHeight > this.showHeight) {
        this.heightChange = true;
      } else {
        this.heightChange = false;
      }
    }
  },
  methods: {
    // throttle和IntersectionObserver 方案结合起来使用
    scrollFunc() {
      const headerDOM = document.getElementById('header');
      if (IntersectionObserver && headerDOM) {
        const observer = new IntersectionObserver(this.handleScroll, {
          // 100%时触发回调函数
          threshold: [1]
        });
        observer.observe(headerDOM);
      } else {
        // window.addEventListener('scroll', throttle(this.handleScroll, 20));
      }
    },
    handleScroll() {
      this.isScroll = true;
      if (this.channelList.length > 1) {
        const headerDOM = document.getElementById('header');
        if (headerDOM) {
          const bottom = headerDOM.getBoundingClientRect().bottom + 10;
          this.tabFixed = bottom <= 0;
        } else {
          this.tabFixed = true;
        }
      }
      clearTimeout(this.timer);
      this.timer = setTimeout(this.isScrollEnd, 500);
      this.t1 = document.documentElement.scrollTop || document.body.scrollTop;
    },
    isScrollEnd() {
      this.t2 = document.documentElement.scrollTop || document.body.scrollTop;
      if (this.t2 === this.t1) {
        this.isScroll = false;
      }
    },
    scrollToTab() {
      const headerDOM = document.getElementById('header');
      const headerHeight = headerDOM ? headerDOM.offsetHeight + 10 : 0;
      const tabNavDom = document.querySelector('.fixed-tab-nav');
      const tabNavHeight = tabNavDom ? tabNavDom.offsetHeight : 0;
      this.totalHeight = headerHeight + tabNavHeight;
      console.log('==totalHeight==', this.totalHeight);
      window.scrollTo(0, this.totalHeight);
    },
    selectTab(index) {
      if (index === this.curTabIndex) return;
      console.log('selectTab===');
      this.activeIndex = index;
      this.curTabIndex = index;
      this.channelId = this.channelList[index].id;
      this.scrollToTab();
      this.resetTabData();
    },
    handleTagClick(index, tabName) {
      console.log(index, tabName);
      if (index === this.curTabIndex) return;
      this.curTabIndex = index;
      this.channelId = this.channelList[index].id;
      this.resetTabData(true);
      if (this.tabFixed) {
        this.scrollToTab();
      }
    },
    sharePoster() {
      this.isShowPoster = true;
    },
    toggleChannel() {
      if (this.tabFixed) {
        if (this.$refs.channelPopupRef) {
          this.$refs.channelPopupRef.showPopup();
        }
        return;
      }
      const listDom = document.querySelector('.productList-wrapper');
      const listBottom = listDom ? listDom.getBoundingClientRect().bottom : 0;
      console.log('listBottom===', listBottom);
      if (this.docHeight < listBottom) {
        const Dom = document.getElementById('tab-nav-wrap');
        const DomT = Dom ? Dom.offsetTop + 10 : 0;
        window.scrollTo(0, DomT);
        this.tabFixed = true;
      }
      if (this.$refs.channelPopupRef) {
        this.$refs.channelPopupRef.showPopup();
      }
    },
    // 下拉刷新
    onDownRefresh() {
      this.resetTabData();
    },
    // 上拉加载
    onLoadMore() {
      if (this.pageNum === 1 || this.isFinished) {
        this.isLoading = false;
        return;
      }
      this.getData(this.curTabIndex);
    },
    resetTabData(bool = false) {
      this.pageNum = 1;
      this.isFinished = false; // 上拉到底过后,再下拉刷新, 触发下拉加载事件
      this.isScroll = false;
      this.list = [];
      if (!bool) {
        this.lifeTabList = [];
      }
      this.getData(this.curTabIndex);
    },
    // 跳商品详情
    goProductDetail(productObj) {
      this.$router.push({
        path: 'productDetail',
        query: {
          productId: productObj.productNo,
          activityNo: productObj.activityNo
        }
      });
    },
    // 分享商品
    // eslint-disable-next-line no-unused-vars
    shareProduct(productObj, index) {
      // const newProductObj = {
      //   ...productObj,
      //   spm: '30.626.8.20.19'
      // };
      // this.setProductShareMixinV2(newProductObj);
    },
    compare(key) {
      // 升序
      return (a, b) => a[key] - b[key];
    },
    sortByLocationOrSort() {
      return (a, b) => {
        let value;
        if (a.location === b.location) {
          value = a.sortValue > b.sortValue ? 1 : -1;
        } else {
          value = a.location > b.location ? 1 : -1;
        }
        return value;
      };
    },
    // 获取会场数据
    getData(curTabIndex = 0) {
      // conference({
      //   channelId: this.channelId || '',
      //   conferenceId: this.conferenceId,
      //   pageNum: this.pageNum,
      //   pageSize: this.pageSize
      // })
      new Promise(resolve => {
        resolve(dataInfo);
      })
        .then(res => {
          const { code, data, message } = res || {};
          if (code === 200) {
            if (this.activeIndex !== curTabIndex) {
              return;
            }
            const {
              headerVO,
              productList,
              activityList,
              pluginCardInfos,
              type
            } = data || {};
            const {
              bgColor,
              title,
              banners,
              icons,
              channelList,
              conferenceSpVos
            } = headerVO || {};
            this.bgColor = bgColor;
            this.conferenceName = title || '';
            this.bannerList = banners || [];
            this.channelList = channelList || [];
            this.type = type; // type 1：活动 2：商品
            // 处理生活频道插卡位数据
            this.lifeTabList = conferenceSpVos || [];
            // 金刚位排序
            if (icons && icons.length > 0) {
              this.diamondList = icons.sort(this.compare('location'));
            } else {
              this.diamondList = [];
            }
            // 插卡位数据处理
            let insertCardList = [];
            if (pluginCardInfos && pluginCardInfos.length > 0) {
              insertCardList = pluginCardInfos
                .map(item => {
                  item.isInsertCard = true;
                  return item;
                })
                .sort(this.sortByLocationOrSort());
            }

            console.log('insertCardList1', insertCardList);
            // 列表数据处理
            let dataList = [];
            if (type === 1) {
              dataList = activityList || [];
            } else {
              dataList = productList || [];
            }
            if (this.pageNum === 1) {
              this.list = dataList;
            } else {
              this.list = this.list.concat(dataList);
            }

            // 判断是否有数据
            /*this.notData =
              this.bannerList.length === 0 &&
              this.diamondList.length === 0 &&
              this.lifeTabList.length === 0 &&
              this.channelList.length === 0 &&
              this.list.length === 0;*/
            this.getShopInfo(true);

            // 搜集列表已存在的插卡Ids
            const cardIds = this.list
              .filter(item => item.isInsertCard)
              .map(item => item.id);
            let insertCardNum = cardIds.length || 0;

            // 判断是否有下一页
            if (dataList.length < this.pageSize) {
              this.isFinished = true;
            } else {
              this.pageNum += 1;
              this.isFinished = false;
            }

            // 剔除列表中存在的插卡
            insertCardList = insertCardList.filter(
              item => !cardIds.includes(item.id)
            );
            const preInsertCardNum = insertCardNum;
            // 将剩余的插卡位数据插入列表中
            // eslint-disable-next-line no-restricted-syntax
            for (const item of insertCardList) {
              // 列表总数据
              const listTotal = this.list.length;
              const location =
                Math.ceil((listTotal - insertCardNum) / this.colType) ===
                item.location
                  ? this.list.length + insertCardNum - preInsertCardNum
                  : item.location * this.colType + insertCardNum;
              // 判断是否能插入插卡位数据
              if (
                Math.ceil((listTotal - insertCardNum) / this.colType) >=
                item.location
              ) {
                this.list.splice(location, 0, item);
                insertCardNum += 1;
              } else {
                break;
              }
            }
            // 修改页面标题为会场名称
            this.setPageTitle();
          } else {
            this.isFinished = true;
            this.$toast.fail(message || '服务异常，请稍后再试');
          }
        })
        .catch(err => {
          this.isFinished = true;
          this.$toast.fail(err && err.message);
        })
        .then(() => {
          this.isRefresh = false;
          this.isLoading = false;
        });
    },
    // 获取用户信息
    getShopInfo(bool) {
      const { data, code } = userInfo || {};
      if (code === 200) {
        const { currentRole, distributorDisable } = data || {};
        // 判断身份
        this.isAgent =
          (currentRole === 3 && !distributorDisable) || currentRole === 4;
        if (bool) {
          this.getSharePosterInfo();
        }
      }
    },
    getSharePosterInfo() {
      const { code, data } = shareInfo || {};
      if (code === 200) {
        const { popStatus, popCount, ...rest } = data || {};
        this.shopInfo = { ...this.shopInfo, ...rest, link: rest.shareLink };
        console.log('this.shopInfo===', this.shopInfo);
        // popStatus 1代表开启
        if (popStatus === 1) {
          // 身份B/弹窗次数大于0/开关（展示）
          if (popCount > 0 && this.isAgent) {
            this.entryShowPoster(popCount);
          }
        }
      }
    },
    init() {
      this.type = '';
      this.pageNum = 1;
      this.channelId = null;
      this.notData = false;
      this.curTabIndex = 0;
      this.activeIndex = 0;
      this.channelList = [];
      this.bannerList = [];
      this.diamondList = [];
      this.list = [];
      this.isFinished = false;
      this.tabFixed = false;
      this.conferenceName = '';
      this.isFirstLoading = true;
      this.lifeTabList = [];
      this.isShowPoster = false;
      this.isAgent = false;
      this.isScroll = false;
      this.shopInfo = {};
    },
    entryShowPoster(popCount) {
      // 是小C 不展示
      if (!this.isAgent) return;
      const { conferenceId, shopId } = this.$route.query;
      // 缓存的key值
      const localKey = `conferencePoster-${conferenceId}-${shopId}`;
      // 从缓存中获取海报已弹窗信息
      let dialogObj = localStorage.getItem(localKey)
        ? JSON.parse(localStorage.getItem(localKey))
        : {};
      // 获取当前年月日
      const date = getYMD();
      // 获取弹过海报次数
      let dialogCount = dialogObj[date] ? Number(dialogObj[date]) : 0;
      if (dialogCount < popCount) {
        if (dialogCount === 0) {
          dialogObj = {};
          localStorage.removeItem(localKey);
        }
        dialogCount += 1;
        dialogObj[date] = dialogCount;
        localStorage.setItem(localKey, JSON.stringify(dialogObj));
        this.sharePoster();
      }
    },
    open() {
      this.disabled = true;
    },
    close() {
      this.disabled = false;
    },
    setPageTitle() {
      if (this.conferenceName) {
        setTimeout(() => {
          window.document.title =
            this.conferenceName.length > 8
              ? `${this.conferenceName.slice(0, 8)}...`
              : this.conferenceName;
        }, 200);
      }
    }
  },
  mounted() {
    const u = navigator.userAgent;
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
    if (isAndroid) {
      window.onresize = () =>
        (() => {
          this.showHeight = document.documentElement.clientHeight;
          console.log('this.showHeight ', this.showHeight);
        })();
    }
  },
  activated() {
    let { conferenceId } = this.$route.query;
    if (!conferenceId) {
      this.$toast('会场id不能为空');
      return;
    }
    window.addEventListener('scroll', this.handleScroll);
    if (this.$route.meta.isNeedRefresh || conferenceId !== this.conferenceId) {
      window.scrollTo(0, 0);
      this.init();
      this.conferenceId = conferenceId;
      this.getData(this.curTabIndex);
    }
    this.$route.meta.isNeedRefresh = false;
    // 设置页面标题
    this.setPageTitle();
  },
  deactivated() {
    window.removeEventListener('scroll', this.handleScroll);
    if (this.isShowPoster) {
      this.isShowPoster = false;
    }
  },
  beforeRouteUpdate(to, from, next) {
    console.log('beforeRouteUpdate===', to, from);
    const { conferenceId } = to.query || {};
    if (conferenceId !== this.conferenceId) {
      window.scrollTo(0, 0);
      this.init();
      this.conferenceId = conferenceId;
      this.getData(this.curTabIndex);
    }
    next();
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isNeedRefresh = from.name === 'index';
    next();
  }
};
</script>
<style lang="scss" scoped>
.common-activity {
  position: relative;
  background-color: #f5f5f5;
  padding-bottom: 56px;

  #header {
    padding: 10px 10px 0;
    margin-bottom: 10px;
  }

  .isFixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 99;
    transition: top 0.3s ease;
  }
  #tab-nav-wrap {
    display: flex;

    .channel-list {
      width: 329px;
    }

    .w100 {
      width: 100%;
    }

    .drop-down {
      width: 46px;
      height: 38px;
      background: #ffffff;
      img {
        width: 46px;
        height: 38px;
      }
    }
  }

  .productList-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px;
  }

  .between {
    justify-content: space-between;
  }
  .col-3 {
    padding: 0 9px;
  }
  .pt48 {
    padding-top: 48px;
  }

  .share-activity-btn {
    position: fixed;
    left: 80px;
    bottom: 16px;
    width: 200px;
    height: 40px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    background: linear-gradient(
      180deg,
      rgba(252, 96, 80, 1) 0%,
      rgba(231, 29, 28, 1) 100%
    );
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.3);
    border-radius: 20px;
    color: white;
    font-size: 16px;
  }

  .van-tab_custom {
    padding-top: 10px;
  }

  .list-min-height {
    min-height: 100vh;
  }
}
</style>

<style lang="scss">
.van-tabs_custom_activity {
  .van-tabs__wrap {
    z-index: 1002;
    height: 38px !important;
  }

  .van-tabs__nav--complete {
    padding-left: 0;
  }

  .van-tab {
    line-height: 38px !important;
    flex-basis: 23% !important;
    padding: 0 8px;
  }
  .van-tabs__line {
    height: 2px !important;
    background-color: #e62525 !important;
    border-radius: 1px !important;
  }

  .van-tab--active {
    font-weight: 400 !important;
    color: #e62525 !important;
  }
}
</style>
